package com.vehiclemanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;  //LambdaQueryWrapper：Lambda表达式查询条件构建器
import com.baomidou.mybatisplus.core.metadata.IPage;                      //IPage：分页数据接口（分页），获取一个数据当前页的对象
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;        //Page：分页插件，用于分页查询
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;      //ServiceImpl：服务实现类，提供基本的CRUD操作
import com.vehiclemanagement.entity.Binding;                                //Binding：绑定关联实体类
import com.vehiclemanagement.entity.Vehicle;                                //Vehicle：车辆实体类
import com.vehiclemanagement.mapper.BindingMapper;                         //BindingMapper：绑定关联映射类
import com.vehiclemanagement.service.BindingService;                      //BindingService：绑定关联服务接口
import org.apache.commons.lang3.StringUtils;                             //StringUtils：字符串处理工具类
import org.springframework.beans.factory.annotation.Autowired;            //Autowired：自动装配注解，用于将Spring容器中的Bean注入到当前类中
import org.springframework.stereotype.Service;                             //Service：服务注解，用于标识这是一个服务类

import java.time.LocalDateTime;                                          //LocalDateTime：日期时间类，用于表示日期和时间

/**
 * 绑定关联服务实现类
 */
@Service
//实现BindingService接口，继承ServiceImpl类，实现BindingMapper映射类，实现Binding实体类
public class BindingServiceImpl extends ServiceImpl<BindingMapper, Binding> implements BindingService {  
    
    //自动装配BindingMapper映射类
    @Autowired
    private BindingMapper bindingMapper;

    //实现BindingService接口的pageBindings方法  
    @Override
    public IPage<Binding> pageBindings(
        Integer current, 
        Integer size, 
        String plateNumber,
        String driverName,
        String fuelCardNumber,
        String etcCardNumber,
        Long vehicleId, 
        Long driverId, 
        Integer status, 
        String sortField, 
        String sortOrder
    ) {
        // 创建分页对象
        Page<Binding> page = new Page<>(current, size);
        
        // 创建自定义SQL条件
        StringBuilder whereSql = new StringBuilder(" b.del_flag = 0 ");
        
        // 添加车牌号查询条件
        if (StringUtils.isNotBlank(plateNumber)) {
            whereSql.append(" AND v.plate_number LIKE '%").append(plateNumber).append("%' ");
        }
        
        // 添加驾驶员姓名查询条件
        if (StringUtils.isNotBlank(driverName)) {
            whereSql.append(" AND d.name LIKE '%").append(driverName).append("%' ");
        }
        
        // 添加加油卡号查询条件
        if (StringUtils.isNotBlank(fuelCardNumber)) {
            whereSql.append(" AND fc.card_number LIKE '%").append(fuelCardNumber).append("%' ");
        }
        
        // 添加ETC卡号查询条件
        if (StringUtils.isNotBlank(etcCardNumber)) {
            whereSql.append(" AND ec.card_number LIKE '%").append(etcCardNumber).append("%' ");
        }
        
        // 添加车辆ID查询条件
        if (vehicleId != null) {
            whereSql.append(" AND b.vehicle_id = ").append(vehicleId);
        }
        
        // 添加驾驶员ID查询条件
        if (driverId != null) {
            whereSql.append(" AND b.driver_id = ").append(driverId);
        }
        
        // 添加状态查询条件
        if (status != null) {
            whereSql.append(" AND b.status = ").append(status);
        }
        
        // 添加排序
        if (StringUtils.isNotBlank(sortField)) {
            String direction = "DESC";
            if (StringUtils.isNotBlank(sortOrder) && "asc".equalsIgnoreCase(sortOrder)) {
                direction = "ASC";
            }
            
            // 根据字段名添加排序
            switch (sortField) {
                case "id":
                    whereSql.append(" ORDER BY b.id ").append(direction);
                    break;
                case "plate_number":
                    whereSql.append(" ORDER BY v.plate_number ").append(direction);
                    break;
                case "driver_name":
                    whereSql.append(" ORDER BY d.name ").append(direction);
                    break;
                case "fuel_card_number":
                    whereSql.append(" ORDER BY fc.card_number ").append(direction);
                    break;
                case "etc_card_number":
                    whereSql.append(" ORDER BY ec.card_number ").append(direction);
                    break;
                case "bind_time":
                    whereSql.append(" ORDER BY b.bind_time ").append(direction);
                    break;
                default:
                    whereSql.append(" ORDER BY b.create_time DESC");
                    break;
            }
        } else {
            // 默认排序
            whereSql.append(" ORDER BY b.create_time DESC");
        }
        
        System.out.println("执行查询SQL条件: " + whereSql.toString());
        
        // 执行查询
        return bindingMapper.selectPageWithInfo(page, whereSql.toString());
    }

    @Override
    public Binding getBindingById(Long id) {
        return bindingMapper.selectById(id);
    }

    @Override
    public boolean existsActiveBinding(Long vehicleId, Long driverId, Long fuelCardId, Long etcCardId) {
        return bindingMapper.existsActiveBinding(vehicleId, driverId, fuelCardId, etcCardId) > 0;
    }

    @Override
    public boolean addBinding(Binding binding) {
        System.out.println("服务层开始添加绑定关联: " + binding);
        
        try {
            // 先检查是否存在有效的绑定关系
            if (existsActiveBinding(binding.getVehicleId(), binding.getDriverId(), binding.getFuelCardId(), binding.getEtcCardId())) {
                System.out.println("添加绑定关联失败：已存在有效的绑定关系");
                return false;
            }
            
            // 设置默认值
            if (binding.getBindTime() == null) {
                binding.setBindTime(LocalDateTime.now());
            }
            if (binding.getCreateTime() == null) {
                binding.setCreateTime(LocalDateTime.now());
            }
            if (binding.getUpdateTime() == null) {
                binding.setUpdateTime(LocalDateTime.now());
            }
            if (binding.getDelFlag() == null) {
                binding.setDelFlag(0);
            }
            if (binding.getStatus() == null) {
                binding.setStatus(1); // 默认绑定中
            }
            
            // 执行插入
            int result = bindingMapper.insert(binding);
            System.out.println("插入结果: " + result + ", 生成的ID: " + binding.getId());
            
            return result > 0;
        } catch (Exception e) {
            System.err.println("添加绑定关联发生异常: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean updateBinding(Binding binding) {
        // 更新时间
        binding.setUpdateTime(LocalDateTime.now());
        
        return bindingMapper.updateById(binding) > 0;
    }

    @Override
    public boolean deleteBinding(Long id) {
        // 使用物理删除
        System.out.println("执行物理删除绑定关联，ID: " + id);
        
        try {
            // 直接物理删除记录
            int result = bindingMapper.deletePhysically(id);
            System.out.println("物理删除结果: " + result);
            return result > 0;
        } catch (Exception e) {
            System.err.println("删除绑定关联时出错: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean isVehicleAlreadyBound(Long vehicleId, Long excludeId) {
        if (vehicleId == null) {
            return false;
        }
        
        LambdaQueryWrapper<Binding> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Binding::getVehicleId, vehicleId)
                   .eq(Binding::getStatus, 1) // 只检查状态为"绑定中"的记录
                   .eq(Binding::getDelFlag, 0); // 未删除的记录
        
        // 如果有需要排除的ID，则加入条件
        if (excludeId != null) {
            queryWrapper.ne(Binding::getId, excludeId);
        }
        
        // 查询符合条件的记录数
        return count(queryWrapper) > 0;
    }
} 